﻿using System;
using FluentNHibernate.Cfg;
using FluentNHibernate.Cfg.Db;
using NHibernate;

namespace DotNet.DevOps.Tasks.Tests.IntegrationTest.Oracle
{
    class OracleConnection
    {
        /*  
         *  Oracle XE Web Admin:   http://Server:6060/apex
         *  Connect: sqlplus SYS/myretuefest@SERVER AS SYSDBA
         */

        private static ISessionFactory _factory;

        static OracleConnection()
        {
            _factory = Fluently.Configure()
                .Database(OracleDataClientConfiguration
                              .Oracle10
                              .ConnectionString("Data Source=SERVER;User Id=sys;Password=myretuefest;DBA Privilege=SYSDBA;"))
                .BuildSessionFactory();
        }

        public static int ExecuteIntScalar(string commandText)
        {
            return ExecuteScalar(commandText, Convert.ToInt32);
        }

        private static T ExecuteScalar<T>(string commandText, Func<object, T> typeConverter)
        {
            using (var session = _factory.OpenSession())
            {
                var cmd = session.Connection.CreateCommand();

                cmd.CommandText = commandText;

                return typeConverter( cmd.ExecuteScalar() );
            }
        }
    }
}
